package znbkTestPaperRdtz.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.lancooznbk.R;

import lancooControl.Control;
import lancooControl.PopupWindowMoreFunction;
import znbkChangeCollection.ChangeCollectionEntityModel;
import znbkChangeCollection.ChangeCollectionPresenter.ChangeCollectionPresenter;
import znbkChangeZsdLearned.presenter.ZnbkSaveLearnedZsdPresenter;
import znbkListRdtz.entity.HeatPointExtensionListEntity;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.base.ILoadPaperView;
import com.example.lancooznbk.view.widget.ClickImageView;
import com.example.lancooznbk.view.widget.FlowLayout;
import com.example.lancooznbk.view.widget.LoadingDialog;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.example.lancooznbk.view.widget.TagAdapter;
import com.example.lancooznbk.view.widget.TagFlowLayout;
import com.example.lancooznbk.view.widget.TagView;
import com.google.gson.Gson;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import lancooControl.AndroidBug5497Workaround;
import tcking.github.com.giraffeplayer.GiraffePlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import znbkListSc.ZnbkPaperScInfor;
import znbkTestPaperBj.entity.NotePaperEntity;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;
import znbkTestPaperRdtz.ZnbkPaperRdtzInfor;
import znbkTestPaperRdtz.entity.HeatPointExtensionPaperEntity;
import znbkTestPaperRdtz.presenter.HeatPointExtensionPaperPresenter;
import znbkTestPaperRdtz.saveRdtzPaper.SaveHeatPointExtensionPaperPresenter;
import znbkTopicType.NoteDetailActivity;

/**
 * Created by Administrator on 2018\3\22 0022.
 */

public class HeatPointExtensionPaperSplActivity extends BaseActivity implements ILoadPaperView<HeatPointExtensionPaperEntity> {

    private ScaleButton mSBtnBack;//返回按钮
    private TextView mTvTittle;
    //    private RelativeLayout RLayoutMoreFouctionMenu;//更多功能菜单
    private ScaleButton mSBtnMore;
    private TextView mTvTypeName;
    private LinearLayout mLayoutBasicInfor;//基本信息：创建时间，推荐人气
    private TextView mTvCreateTime;
    private TextView mTvRecommendNumberOfTimes;
    private LinearLayout mLayoutTools;//工具栏：笔记，知识点
    private ClickImageView mCivNote;
    private ClickImageView mCivKnowledgePoint;
    public static boolean IsHaveNoteRdtzSpl = false;

    GiraffePlayer player;
    private HeatPointExtensionListEntity.ResourceBean mEntity;
    public static final  String PAPER_ENTITY = "paperEntity";
    public static final String PAPER_FROM = "paperFrom";
    public int mQuesOrPaperFrom;
    HeatPointExtensionPaperPresenter mPresenter;
    public static HeatPointExtensionPaperEntity mEntityRdtz;
    /*
   * 获取作文题用户相关信息
   * */
    private String ResName = "";
    private String ResTypeName = "";
    private String CreateTime = "";
    private int RecommendNumberOfTimes = -1;
    public String VideoPath = "";

    public  static void launch(BaseFragment mContext, HeatPointExtensionListEntity.ResourceBean entity, @ZnbkPaperDef.PaperFrom int quesOrPaperFrom){
        ZnbkPaperRdtzInfor.CreatTime = entity.getUpdateTime();
        ZnbkPaperRdtzInfor.RecommendNumberOfTimes = entity.getHotIndex();
        ZnbkPaperRdtzInfor.HotType = entity.getHotType();
        ZnbkPaperRdtzInfor.ResType = entity.getResType();
        ZnbkPaperRdtzInfor.Title = entity.getTitle();
        ZnbkPaperRdtzInfor.ResID = entity.getItemID();
        if(entity.getResType().equals("1")||
                entity.getResType().equals("2")||
                entity.getResType().equals("3")||
                entity.getResType().equals("4")||
                entity.getResType().equals("5")||
                entity.getResType().equals("6")) {
            ZnbkPaperRdtzInfor.Flag = 1;
        }else{
            ZnbkPaperRdtzInfor.Flag = 0;
        }

        if(entity.getResType().equals("Q")) {
            ZnbkPaperInfor.ResFlag = 0;
        }else{
            ZnbkPaperInfor.ResFlag = 1;
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable(PAPER_ENTITY,entity);
        bundle.putInt(PAPER_FROM,quesOrPaperFrom);
        Intent intent = new Intent(mContext.getContext(), HeatPointExtensionPaperSplActivity.class);
        intent.putExtras(bundle);
        mContext.startActivityForResult(intent,1);
    }

    @Override
    public int attachLayoutRes() {
        return R.layout.activity_paper_spl;
    }

    @Override
    protected void initViews() {

        initView();

        AndroidBug5497Workaround.assistActivity(this);
        mPresenter = new HeatPointExtensionPaperPresenter(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null){
            mEntity = (HeatPointExtensionListEntity.ResourceBean) bundle.getSerializable(PAPER_ENTITY);
            mQuesOrPaperFrom = bundle.getInt(PAPER_FROM);
        }

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }


        player = new GiraffePlayer(this);
        player.onComplete(new Runnable() {
            @Override
            public void run() {
                //callback when video is finish
                Toast.makeText(getApplicationContext(), "video play completed", Toast.LENGTH_SHORT).show();
            }
        }).onInfo(new GiraffePlayer.OnInfoListener() {
            @Override
            public void onInfo(int what, int extra) {
                switch (what) {
                    case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                        //do something when buffering start
                        break;
                    case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                        //do something when buffering end
                        break;
                }
            }
        }).onError(new GiraffePlayer.OnErrorListener() {
            @Override
            public void onError(int what, int extra) {
                Toast.makeText(getApplicationContext(), "video play error",Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        mSBtnMore.setVisibility(View.VISIBLE);
        ZnbkPaperRdtzInfor.IsFromSpl = true;
        mPresenter.getData(isRefresh);
    }

    /*
 * 初始化界面控件
 * */
    private void initView(){

        /*
        * 返回按钮菜单相关设置
        * */
        mSBtnBack = (ScaleButton) findViewById(R.id.sbtn_back);
        mSBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                savePaperRdtz();
            }
        });


        /*
        * 页面头部-》收藏详情：mTvTittle
        * */
        mTvTittle = (TextView) findViewById(R.id.tv_title);
        mTvTittle.setText(R.string.znbk_titleHeatPointExtension);

        /*
        * 更多功能按钮菜单相关信息
        * */
        mSBtnMore = (ScaleButton) findViewById(R.id.sbtn_more);
        mSBtnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEntityRdtz!=null) {
                    initPopupWindowMoreFunction();
                }else {
                    Toast.makeText(getApplicationContext(),"数据加载中，请稍后重试...",Toast.LENGTH_SHORT).show();
                }
            }
        });

        mTvTypeName = (TextView) findViewById(R.id.tv_typeName);
        mLayoutBasicInfor = (LinearLayout) findViewById(R.id.layout_basicInfor);
        /*
        * 显示基本信息
        * */
        mLayoutBasicInfor.setVisibility(View.VISIBLE);
        mTvCreateTime = (TextView) findViewById(R.id.tv_createTime);
        mTvRecommendNumberOfTimes = (TextView) findViewById(R.id.tv_recommendNumberOfTimer);
        mLayoutTools = (LinearLayout) findViewById(R.id.layout_tools);
        /*
        * 显示工具栏
        * */
        mLayoutTools.setVisibility(View.VISIBLE);
        mCivNote = (ClickImageView) findViewById(R.id.civ_note);

        mCivKnowledgePoint = (ClickImageView) findViewById(R.id.civ_knowledgePoint);
        mCivKnowledgePoint.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                showKnowledgePointPopupWindow(mCivKnowledgePoint, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
        if (IsHaveNoteRdtzSpl) {
            //获取已有学生笔记内容,显示查看图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
        } else {
            //显示写入笔记图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void loadPaperData(HeatPointExtensionPaperEntity data) {
        mEntityRdtz = data;

        /*
        * 显示资源概况
        * */
        ResName = mEntityRdtz.getResFromTK().getResName();
        if (ResName.equals("")) {
            ResName = mEntityRdtz.getResFromTK().getResTypeName();
        }

        /*
        * 资源类型
        * */
        ResTypeName = mEntityRdtz.getResFromTK().getResTypeName();

        /*
        * 显示题型名称
        * */
        mTvTypeName.setText(ResName);

        /*
        * 资源创建时间
        * */
        CreateTime = ZnbkPaperRdtzInfor.CreatTime;
        if (!CreateTime.equals("")) {
            mTvCreateTime.setText("创建时间：" + CreateTime);
        } else {
            mTvCreateTime.setVisibility(View.GONE);
        }

        /*
        * 推荐人气
        * */
        RecommendNumberOfTimes = ZnbkPaperRdtzInfor.RecommendNumberOfTimes;
        if (RecommendNumberOfTimes != -1) {
//            mTvRecommendNumberOfTimes.setText("推荐人气：" + RecommendNumberOfTimes + "次");
            String recommendPersonTime = String.format(getHolderActivity().getString(R.string.rdtz_recommendPersonTime), String.valueOf(RecommendNumberOfTimes));
            mTvRecommendNumberOfTimes.setText(recommendPersonTime);
        } else {
            mTvRecommendNumberOfTimes.setVisibility(View.GONE);
        }

        if (!mEntityRdtz.getNoteId().equals("")) {
            //获取已有学生笔记内容,显示查看图标
            IsHaveNoteRdtzSpl = true;
        } else {
            //显示写入笔记图标
            IsHaveNoteRdtzSpl = false;
        }


        String ResType = mEntityRdtz.getResFromTK().getResType();
        final String TypeNo = mEntityRdtz.getResFromTK().getTypeNo();
        final String QuesID = mEntityRdtz.getResFromTK().getQuesID();
        int NoteFlag= -1;

        if (ResType.equals("Q")) {
            NoteFlag = 0;
            ResType = TypeNo;
        } else {
            NoteFlag = 1;
        }

        if (IsHaveNoteRdtzSpl) {
            //获取已有学生笔记内容,显示查看图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
        } else {
            //显示写入笔记图标
            mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
        }

        final int finalNoteFlag = NoteFlag;
        mCivNote.setClickListener(new ClickImageView.ClickListener() {
            @Override
            public void onClick() {
                getNotesData(QuesID, finalNoteFlag);
            }
        });



        /*
        * 视频路径
        * */
        VideoPath = mEntityRdtz.getResFromTK().getVedioList().get(0).getAudioPath();
        player.play(VideoPath);
        player.setShowNavIcon(false);


    }

    /*
* 监听系统返回事件
* */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            savePaperRdtz();
            return false;
        }
        return false;
    }

    @Override
    public void loadComplete(boolean hasComplete) {

    }

    @Override
    public void openExamReportDialog() {

    }

    @Override
    public void openAssessDialog() {

    }

    @Override
    public void updatingResult(boolean isSucceed) {

    }

    @Override
    public void updatingReportResult(boolean isReportSucceed) {

    }

    @Override
    public LoadingDialog getLoadingDialog() {
        return null;
    }


    /******************************************更多功能popupwindow****************************************************/

    private PopupWindowMoreFunction mPopupWindowMoreFunction;
    private void initPopupWindowMoreFunction(){
        if (mPopupWindowMoreFunction == null) {
            //自定义的单击事件
            OnClickLintener paramOnClickListener = new OnClickLintener();
            mPopupWindowMoreFunction = new PopupWindowMoreFunction(this, paramOnClickListener, Control.dip2px(this,140), Control.dip2px(this,80));
            //监听窗口的焦点事件，点击窗口外面则取消显示
            mPopupWindowMoreFunction.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        mPopupWindowMoreFunction.dismiss();
                    }
                }
            });
        }


        //显示当前试题的收藏情况
        if(!mEntityRdtz.isIsFavourite()) {
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
        }else if(mEntityRdtz.isIsFavourite()){
            PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
            PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
            PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
        }

//设置默认获取焦点
        mPopupWindowMoreFunction.setFocusable(true);
//以某个控件的x和y的偏移量位置开始显示窗口
        mPopupWindowMoreFunction.showAsDropDown(mSBtnMore, Control.dip2px(this,-120), Control.dip2px(this,15));
//如果窗口存在，则更新
        mPopupWindowMoreFunction.update();
    }
    class OnClickLintener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_dictionary:
                    System.out.println("=======电子词典=========");
                    mPopupWindowMoreFunction.dismiss();
                    startActivity(new Intent(getApplicationContext(), DictionaryActicity.class));
                    break;
                case R.id.layout_difficult_question:
                    System.out.println("=======收藏与否=========");
                    int CollectionFlag = -1;
                    if(!mEntityRdtz.isIsFavourite()) {
                        CollectionFlag = 1;
                        mEntityRdtz.setIsFavourite(true);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_focus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("取消收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.yellow));
                    }else if(mEntityRdtz.isIsFavourite()){
                        CollectionFlag = 0;
                        mEntityRdtz.setIsFavourite(false);
                        PopupWindowMoreFunction.ImvDifficultQuestion.setBackgroundResource(R.mipmap.image_collect_unfocus);
                        PopupWindowMoreFunction.TvDifficultQuestion.setText("加入收藏");
                        PopupWindowMoreFunction.TvDifficultQuestion.setTextColor(getResources().getColor(R.color.white));
                    }
                    String QuesID = mEntityRdtz.getResID();

                    String Theme = "";
                    if(!mEntityRdtz.getResFromTK().getQuesBrief().equals("")){
                        Theme = mEntityRdtz.getResFromTK().getQuesBrief();
                    }else{
                        if(mEntityRdtz.getResFromTK().getChildList().size()>0) {
                            if (!mEntityRdtz.getResFromTK().getChildList().get(0).getChildAsk().equals("")) {
                                Theme = mEntityRdtz.getResFromTK().getChildList().get(0).getChildAsk();
                            } else {
                                Theme = mEntityRdtz.getResFromTK().getChildList().get(0).getSubChildList().get(0).getSubChildAsk();
                            }
                        }
                    }
                    String GenreID =  mEntityRdtz.getResFromTK().getGenreID();
                    String TypeNo =  mEntityRdtz.getResFromTK().getTypeNo();
                    String ResType =  mEntityRdtz.getResFromTK().getResType();
                    if(ResType.equals("Q")){
                        ResType =  TypeNo;
                    }

                    ZnbkPaperScInfor.changeCollectionEntityModel =  new ChangeCollectionEntityModel(CollectionFlag,
                            GenreID,QuesID,ResType, UserInfo.StageNo, UserInfo.StuId,UserInfo.SubjectId,Theme,TypeNo);

                    changeCollection();
                    break;

                default:
                    break;
            }

        }

    }


    /*
    * 加入收藏、取消收藏
    * */
    ChangeCollectionPresenter mChangeCollectionPresenter;
    private void changeCollection(){
        mChangeCollectionPresenter = new ChangeCollectionPresenter(this,mQuesOrPaperFrom);
        mChangeCollectionPresenter.getData(false);
    }
    /*************************************************************************************************************/

    /*****************************************************************************************************/
    /***查看笔记内容*******/
    PopupWindow popWinNotes = null;
    TextView TvNotes;
    ScaleButton SBtnChangeNotes;
    public PopupWindow showNotesPopupWindow(final View anchorView, final String noteContent,final String noteID) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_notes, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
        popWinNotes = new PopupWindow(contentView,
                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        TvNotes = (TextView) contentView.findViewById(R.id.tv_notes);
        TvNotes.setText(noteContent);

        SBtnChangeNotes = (ScaleButton) contentView.findViewById(R.id.sbtn_change_notes);
        SBtnChangeNotes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinNotes.dismiss();

                String Title = mEntityRdtz.getResFromTK().getQuesBrief();
                String ResType = mEntityRdtz.getResFromTK().getResType();
                String TypeNo = mEntityRdtz.getResFromTK().getTypeNo();
                String QuesID = mEntityRdtz.getResFromTK().getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }

                NoteDetailActivity.launch(HeatPointExtensionPaperSplActivity.this,noteContent,Title,noteID,ResType,QuesID,
                        ZnbkPaperDef.FROM_HEAT_POINT_EXTENSION_SPL);


            }
        });

        popWinNotes = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinNotes, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinNotes.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinNotes.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinNotes.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinNotes.setFocusable(true);
//        popWinNotes.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;   // 这里面拦截不到返回键
//            }
//        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinNotes.showAsDropDown(anchorView);


        return popWinNotes;
    }

    /*****fast-json 解析笔记内容******/
    private void getNotesData(String QuesID,int NoteFlag){

        String url = ZnbkPaperInfor.BaseHttpAdress+"api/ZNBK/W_ZNBK_GetPersonalNote?"+"StuID="+ UserInfo.StuId+
                "&SubjectID="+UserInfo.SubjectId+"&StageNo="+ UserInfo.StageNo+"&QuesID="+QuesID+
                "&IsReplace=true"+"&Flag="+NoteFlag;

        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String arg0) {
                Log.e("==wgl==",""+arg0);//获取完成后，在 http://www.bejson.com/ 解析查看数据
                dealData(arg0);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                final String NoteID = mEntityRdtz.getResFromTK().getNoteId();
                String ResType = mEntityRdtz.getResFromTK().getResType();
                String TypeNo =mEntityRdtz.getResFromTK().getTypeNo();
                final String Title =mEntityRdtz.getResFromTK().getQuesBrief();
                final String QuesID = mEntityRdtz.getResFromTK().getQuesID();
                if (ResType.equals("Q")) {
                    ResType = TypeNo;
                }
                NoteDetailActivity.launch(HeatPointExtensionPaperSplActivity.this,"",Title,NoteID, ResType,QuesID,
                        ZnbkPaperDef.FROM_HEAT_POINT_EXTENSION_SPL);
            }
        });
        new Volley().newRequestQueue(HeatPointExtensionPaperSplActivity.this).add(request);
    }


    //处理数据
    private void dealData(String result){
        Gson gson = new Gson();
        NotePaperEntity notePaperEntity = gson.fromJson(result, NotePaperEntity.class); // data 转实体
        String NoteContent = notePaperEntity.getModelNoteList().getContent();
        String NoteID = notePaperEntity.getModelNoteList().getNoteID();

        if(!NoteContent.equals("")) {
            showNotesPopupWindow(mCivNote,NoteContent,NoteID);
        }

    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {
        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        int pos[] = new int[2];
        contentView.getLocationOnScreen(pos);
        int popLeftPos = pos[0];
        anchorView.getLocationOnScreen(pos);
        int anchorLeftPos = pos[0];
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;
        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }

/**************************************************************************************************************************/
    /******************************************查看知识点学习情况****************************************************/
    PopupWindow popWinKnowledgePoint = null;
    private TagFlowLayout mFlowLayout;
    private TextView TvKnowledgePointTitle;
    public PopupWindow showKnowledgePointPopupWindow(final View anchorView, final View.OnClickListener onClickListener) {
        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_knowledge_point, null);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
//        final PopupWindow popupWindow = new PopupWindow(contentView,
//                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        mFlowLayout = (TagFlowLayout) contentView.findViewById(R.id.id_flowlayout);
        TvKnowledgePointTitle = (TextView) contentView.findViewById(R.id.tv_knowledge_point_title);

        popWinKnowledgePoint = new PopupWindow(contentView,
                FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWinKnowledgePoint.dismiss();
                popWinKnowledgePoint = null;
                onClickListener.onClick(v);
            }
        });

        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popWinKnowledgePoint, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popWinKnowledgePoint.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popWinKnowledgePoint.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popWinKnowledgePoint.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popWinKnowledgePoint.setFocusable(false);
        popWinKnowledgePoint.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;   // 这里面拦截不到返回键
            }
        });
        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popWinKnowledgePoint.showAsDropDown(anchorView);

        initKnowledgePoint();

        return popWinKnowledgePoint;
    }

    /*
    * 获取知识点学习情况
    * */
    private List<String> AllTagsPosition;//整个标签存放集合
    private HashMap<Integer, Boolean> map;//记录选择的位置
    private void initKnowledgePoint(){

        AllTagsPosition = new ArrayList<>(0);
        map = new HashMap<>(0);

        int sumKnowledgePoint = mEntityRdtz.getResFromTK().getImportantZSD().size();
        for (int i = 0; i < sumKnowledgePoint; i++) {
            AllTagsPosition.add(mEntityRdtz.getResFromTK().getImportantZSD().get(i).getZSDName());
        }

        for(int i=0;i<AllTagsPosition.size();i++){
            if(!mEntityRdtz.getResFromTK().getImportantZSD().get(i).getUpdateTime().equals("")){
                map.put(i,true);
            }else{
                map.put(i,false);
            }
        }


        mFlowLayout.setAdapter(new TagAdapter<String>(AllTagsPosition.toArray(new String[AllTagsPosition.size()])) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(getHolderActivity()).inflate(R.layout.view_textview,mFlowLayout,false);
                tv.setText(s);
                return tv;
            }

        });//

        mFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                ((TagView)view).setChecked(true);

                int LeanedKnowledge2 =0;

                ZnbkPaperInfor.ZSDName = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDName();
                ZnbkPaperInfor.ZSDCode = mEntityRdtz.getResFromTK().getImportantZSD().get(position).getZSDCode();

                if(mEntityRdtz.getResFromTK().getImportantZSD().get(position).getUpdateTime().equals("")){

                    if(!map.get(position)) {
                        map.put(position, true);
                    }

                }

                for (int i = 0; i < AllTagsPosition.size(); i++) {
                    if (map.get(i)) {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                        LeanedKnowledge2++;
                    }else {
                        ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
                    }
                }



                TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+AllTagsPosition.size()+
                        "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge2+"</middle></middle></font>"+"个,未学习"+
                        "<font color='#ff323d'><middle><middle>"+(AllTagsPosition.size()-LeanedKnowledge2)+"</middle></middle></font>"+"个)"));


                ZnbkSaveLearnedZsd();
                DictionaryActicity.startWithContent(getHolderActivity(),AllTagsPosition.get(position));

                return false;
            }
        });


        int LeanedKnowledge1 = 0;
        for (int i = 0; i < AllTagsPosition.size(); i++) {
            if (map.get(i)) {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(true);
                LeanedKnowledge1++;
            }else {
                ((TagView)mFlowLayout.getChildAt(i)).setChecked(false);
            }
        }

        TvKnowledgePointTitle.setText(Html.fromHtml("知识点(共 "+sumKnowledgePoint+
                "个,已学习"+"<font color='#ff323d'><middle><middle>"+LeanedKnowledge1+"</middle></middle></font>"+"个,未学习"+
                "<font color='#ff323d'><middle><middle>"+(sumKnowledgePoint-LeanedKnowledge1)+"</middle></middle></font>"+"个)"));

    }
    /*
    * 保存一血知识点
    * */
    ZnbkSaveLearnedZsdPresenter mZnbkSaveLearnedZsdPresenter;
    public void ZnbkSaveLearnedZsd(){
        mZnbkSaveLearnedZsdPresenter = new ZnbkSaveLearnedZsdPresenter((ILoadPaperView) getHolderActivity(),mQuesOrPaperFrom);
        mZnbkSaveLearnedZsdPresenter.getData(false);
    }


    /*
* 保存单道试题作答信息
* */
    SaveHeatPointExtensionPaperPresenter mSaveHeatPointExtensionPaperPresenter;
    private void savePaperRdtz(){
        mSaveHeatPointExtensionPaperPresenter = new SaveHeatPointExtensionPaperPresenter(this,mQuesOrPaperFrom);
        mSaveHeatPointExtensionPaperPresenter.getData(false);
    }

}